package com.dhcc.DRGsHosp.infra.util.license;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

public class AESFileReadWrite {
	private String dir = null;
	private String fileName = null;
	private String path = null;

	public AESFileReadWrite(String path) {
		this.path = path;
		this.dir = path.substring(0, path.lastIndexOf("\\") + 1);
		this.setFileName(path.substring(path.lastIndexOf("\\") + 1,path.length() - 1));
		checkFile();
	}

	public void write(Map<String, String> map) {
		String str = "";
		for (String key : map.keySet()) {
			str = str + key + "::" + (String) map.get(key) + ",";
		}
		System.out.println(str);
		str = AESUtil.encrypt(str);
		writeLocalConfig(str);
	}

	public String read() {
		String data = readLocalConfig();
		return AESUtil.decrypt(data);
	}

	public Map<String, String> read2Map() {
		String data = readLocalConfig();
		String str = AESUtil.decrypt(data);
		String[] strs = str.split(",");
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < strs.length; i++) {
			String[] step = strs[i].split("::");
			map.put(step[0], step[1]);
		}
		return map;
	}

	private void checkFile() {
		try {
			File dirFile = new File(this.dir);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			File file = new File(this.path);
			if (!file.exists())
				file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void writeLocalConfig(String str) {
		try {
			FileOutputStream stream = new FileOutputStream(this.path);
			OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
			writer.write(str);
			writer.close();
			stream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String readLocalConfig() {
		try {
			FileInputStream inStream = new FileInputStream(this.path);
			StringBuffer sb = new StringBuffer();
			BufferedReader bufferReader = new BufferedReader(
					new InputStreamReader(inStream, "UTF-8"));
			String str = null;
			while ((str = bufferReader.readLine()) != null) {
				sb.append(str);
			}
			if ((sb == null) || (sb.length() == 0)) {
				inStream.close();
				return null;
			}
			inStream.close();
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @return the fileName
	 */
	public String getFileName() {
		return fileName;
	}

	/**
	 * @param fileName
	 *            the fileName to set
	 */
	private void setFileName(String fileName) {
		this.fileName = fileName;
	}
}